//
//  BKPermission.swift
//  dysaidao
//
//  Created by 王锦发 on 2021/10/6.
//  Copyright © 2021 王锦发. All rights reserved.
//

import UIKit
import AVFoundation
import Photos
import MediaPlayer

class BKPermission: NSObject {
    
    enum BKPermissionType: String {
        case photoLibrary = "照片"
        case camera = "相机"
        
        var msg: String {
            switch self {
            case .photoLibrary: return "请前往「设置—隐私—照片」中打开开关。"
            case .camera: return "请前往「设置—隐私—相机」中打开开关。"
            }
        }
    }
    
    /// 是否允许权限
    static func isAllowed(_ type: BKPermissionType) -> Bool {
        let manager = self.getManagerForPermission(type)
        return manager.isAuthorized
    }
    
    /// 是否拒绝权限
    static func isDenied(_ type: BKPermissionType) -> Bool {
        let manager = self.getManagerForPermission(type)
        return manager.isDenied
    }
    
    /// 是否是【下次询问或在我共享时】【允许一次】【每次询问】
    static func isNotDetermined(_ type: BKPermissionType) -> Bool {
        let manager = self.getManagerForPermission(type)
        return manager.isNotDetermined
    }
    
    /// 请求权限
    static func request(_ type: BKPermissionType, completion callback: ((BKAuthorizationStatus) -> Void)? = nil) {
        let manager = self.getManagerForPermission(type)
        manager.request { status in
            DispatchQueue.main.async {
                if status.isNotSupport {
                    HintTool.toast("当前设备不支持\(type.rawValue)!")
                }
                if status == .denied {
                    self.openSettings(type)
                }
                callback?(status)
            }
        }
    }
    
    /// 请求一组权限
    static func requests(_ types: [BKPermissionType], completion: @escaping (_ allAuthorized: Bool) -> Void) {
        let group = DispatchGroup()
        var allAuthorized = true
        
        for type in types {
            group.enter()
            request(type) { status in
                if !status.isAuthorized {
                    allAuthorized = false
                }
                group.leave()
            }
        }
        
        group.notify(queue: .main) {
            completion(allAuthorized)
        }
    }
    
}

// MARK: - Private
extension BKPermission {
    
    private static func getManagerForPermission(_ type: BKPermissionType) -> BKPermissionInterface {
        switch type {
        case .photoLibrary: return BKPhotoLibraryPermission()
        case .camera: return BKCameraPermission()
        }
    }
    
    private static func openSettings(_ type: BKPermissionType) {
        UIAlertController.showTwoAlertInRoot(title: "\(kAppName)\(type.rawValue)已关闭", msg: type.msg, okTitle: "设置") { _ in
            CommonTool.openSettings()
        }
    }
    
}
